package com.alen.websocket

import android.content.Context
import com.alen.websocket.util.LogUtil
import com.alen.websocket.util.NetworkObserver

object WebSocketKit {

    private const val defaultTag = "Default"

    private val netObserver = NetObserver()

    lateinit var context: Context

    private val clientCache = mutableMapOf<String, WebSocketClient>()

    fun defaultClient(): WebSocketClient {
        return clientForTag(defaultTag)
    }

    fun clientForTag(tag: String): WebSocketClient {
        var client = clientCache[tag]
        if (client == null) {
            client = WebSocketClient()
            clientCache[tag] = client
        }
        return client
    }

    fun removeClient(tag:String){
        var client = clientCache[tag]
        if (client != null) {
            client.close()
            clientCache.remove(tag)
        }
    }

    fun init(context: Context,showLog:Boolean = false) {
        WebSocketKit.context = context.applicationContext
        NetworkObserver.NetworkChangeReceiver.registerReceiver(context)
        NetworkObserver.NetworkChangeReceiver.addObserver(netObserver)
        LogUtil.IS_DEBUG = showLog
    }

    fun reInit(){
        NetworkObserver.NetworkChangeReceiver.registerReceiver(context)
        NetworkObserver.NetworkChangeReceiver.removeObserver(netObserver)
        clientCache.forEach {
            val client = it.value
            client.close()
        }
        clientCache.clear()
    }

    private fun reconnect(){
        clientCache.forEach {
            val client = it.value
            client.reconnect()
        }
    }

    enum class SocketState(state:Int){
        Uninit(0),Opening(1),Open(2),Closing(3),Closed(4);
    }

    internal class NetObserver : NetworkObserver.NetStateChangeObserver {
        override fun onDisconnect() {

        }

        override fun onMobileConnect() {
            reconnect()
        }

        override fun onWifiConnect() {
            reconnect()
        }
    }

}